package com.bishe.app.modules.menu.service.impl;

import com.bishe.app.core.enums.IsDel;
import com.bishe.app.modules.menu.entity.Menu;
import com.bishe.app.modules.menu.mapper.MenuMapper;
import com.bishe.app.modules.menu.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-03-13
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<Long> getAllMenuId(Long parentId) {
        Menu one = lambdaQuery().eq(Menu::getIsDel, IsDel.N.getCode())
                .eq(Menu::getId, parentId)
                .one();

        if (Objects.isNull(one)) {
            return new ArrayList<>();
        }

        List<Long> allChildIdList = new ArrayList<>();
        visitChild(allChildIdList, parentId);
        return allChildIdList;
    }


    private void visitChild(List<Long> allChildIdList, Long parentId) {
        List<Menu> menuList = lambdaQuery().eq(Menu::getIsDel, IsDel.N.getCode())
                .eq(Menu::getParentId, parentId)
                .list();
        if (CollectionUtils.isEmpty(menuList)) {
            return;
        }

        List<Long> childIds = menuList.stream().map(Menu::getId)
                .collect(Collectors.toList());

        allChildIdList.addAll(childIds);

        for (Long childId : childIds) {
            visitChild(allChildIdList, childId);
        }
    }
}
